<?php


namespace App\Http\Controllers\Admin\Game;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use function Clue\StreamFilter\fun;

use Illuminate\Support\Facades\DB;


//用户管理
class GameUserController extends BaseController
{

    /**
     * @api {get} /guessing/user 用户信息查询
     * @apiVersion 0.1.0
     * @apiName 用户信息查询
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {Int}                     user_id 用户id （选填）
     * @apiParam {String}                     nickname 用户昵称2 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 999900,
     * "current_page": 1,
     * "last_page": 499950,
     * "list": [
     * {
     * "id": 100,
     * "nickname": "",//昵称
     * "avatar": "",//头像
     * "exp": 0,//经验
     * "balance": 993283,//蓝砖数量
     * "reward": 923,//绑钻数量
     * "balance_total": 0,
     * "reward_total": 923,//总产出绑钻

     * 总投入蓝砖=（balance_total - balance）
     * "reward_buy_total": 0,//合成消耗绑钻   盈亏=用户总产出（reward_total）-总投入蓝砖（balance_total - balance）

     * "created_at": "2021-07-30 18:30:44.122988",
     * "updated_at": "2021-08-02 09:22:35.024416"
     * },
     * {
     * "id": 101,
     * "nickname": "",
     * "avatar": "",
     * "exp": 0,
     * "balance": 995734,
     * "reward": 656,
     * "balance_total": 0,
     * "reward_total": 656,
     * "reward_buy_total": 0,
     * "created_at": "2021-07-30 16:41:10.863956",
     * "updated_at": "2021-08-01 23:51:02.275737"
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function userGameList(Request $request)
    {
        $data = $request->only(['page', 'page_size', 'user_id', 'nickname']);

        $va = app('validator')->make($data, [
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:20',
            'user_id' => 'integer|min:1',//开始时间
            'nickname' => 'string|max:255',//结束时间
        ]);
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 20;
        if (!empty($data['user_id'])) {
            $where[] = ['id', '=', $data['user_id']];
        }
        if (!empty($data['nickname'])) {
            $where[] = ['nickname', 'like', '%' . $data['nickname'] . '%'];
        }
        if (isset($where)) {
            $list = app('model_game_user')
                ->where($where)
                ->paginate($data['page_size'], ['*'], '', $data['page'])->toArray();
        } else {
            $list = app('model_game_user')
                ->paginate($data['page_size'], ['*'], '', $data['page'])->toArray();
        }
        $result = [
            'total' => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page' => $list['last_page'] ?? 1,
            'list' => $list['data']
        ];
        return Response::sendData($result);
    }

    //游戏纪录查询

    /**
     * @api {get} /guessing/user/log 游戏纪录查询 + 开奖配置-》开奖详情
     * @apiVersion 0.1.0
     * @apiName 游戏纪录查询
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     round_id 纪录id （必填）
     * @apiParam {Int}                     user_id  （选填）
     * @apiParam {String}                  nickname 用户昵称（选填）
     * @apiParam {Int}                     start_time 开始时间 （选填）
     * @apiParam {Int}                     end_time 结束时间 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "id": 291481,
     * "nickname": "",
     * "avatar": "",
     * "exp": 0,
     * "hit_slot": 8,//命中卡槽 开奖情况
     * "balance": 984593,
     * "reward": 6061,
     * "balance_total": 0,
     * "reward_total": 6061,
     * "reward_buy_total": 0,
     * "created_at": "2021-07-30 13:17:41.828859",
     * "updated_at": "2021-08-04 08:09:15.325069",
     * "bet": [
     * {
     * "user_id": 291481,
     * "round_id": 20210730131800,
     * "slot": 1,//投注位置
     * "input": 108,//该槽位投入
     * "output": 1620//投入获利,
     * "created_at": "2021-07-30 13:17:41.832021"//投注时间
     * },
     * {
     * "user_id": 291481,
     * "round_id": 20210730131800,
     * "slot": 5,
     * "input": 528,
     * "output": 3696
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function gamelog(Request $request)
    {

        $data = $request->only(['round_id', 'user_id', 'nickname', 'start_time', 'end_time']);
        $va = app('validator')->make($data, [
            'user_id' => 'integer|min:1',
            'round_id' => 'required|integer|min:1',
            'nickname' => 'string|max:32',
            'start_time' => 'integer|min:1',
            'end_time' => 'integer|min:1'
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }

        $data['nickname'] = $data['nickname'] ?? '';
        if (!isset($data['nickname']) && !isset($data['user_id'])) {
            throw  new BasicException(10001, '用户信息必填一个');
        }

        if (isset($data['user_id'])) {
            $where[] = ['id', '=', $data['user_id']];
        }
        if (isset($data['nickname'])) {
            $where [] = ['nickname', 'like', '%' . $data['nickname'] . '%'];
        }

        if (isset($data['start_time'])) {
            $where[] = ['created_at', '>', date('Y-m-d H:i:s', $data['start_time'])];
        }

        if (isset($data['end_time'])) {
            $where[] = ['created_at', '<', date('Y-m-d H:i:s', $data['end_time'])];
        }
        $whereHas[] = ['round_id', '=', $data['round_id']];
        $roundInfo = app('model_game_round')->where('id', $data['round_id'])->first();

        if (empty($roundInfo)) {
            throw  new BasicException(10001, '游戏轮号错误');
        }


        $list = app('model_game_user')
            ->where($where)
            ->with(['bet' => function ($query) use ($data) {
                $query->select(['user_id', 'round_id', 'slot', 'input', 'output', 'created_at'])->where('round_id', '=', $data['round_id']);
            }])
            ->first();


        if (empty($list)) {
            return Response::sendData($list);
        }


        $list['hit_slot'] = $roundInfo->toArray()['hit_slot'];

        return Response::sendData($list);


    }


    //游戏纪录查询 多行

    /**
     * @api {get} /guessing/user/loglist /游戏纪录查询 多行
     * @apiVersion 0.1.0
     * @apiName 游戏纪录查询
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {Int}                     user_id  （选填）
     * @apiParam {String}                  nickname 用户昵称（选填）user_id与nickname必须有一个填写
     * @apiParam {Int}                     start_time 开始时间 （选填）
     * @apiParam {Int}                     end_time 结束时间 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 33,
     * "current_page": 1,
     * "last_page": 17,
     * "userInfo": {
     * "id": 1309874,//所有列通用id
     * "nickname": "主惜萱3409775"//所有列通用昵称
     * }
     * "list": [
     * {
     * "id": 20210811174440,
     * "hit_slot": 3,
     * "created_at": "2021-08-11 17:44:40.070322",
     * //本次投入为该json对象中的bet.input总和
     * //本次产出为该json对象中的bet.output总和
     * "bet": [
     * "round_id": 20210811174440,
     * "slot": 1,//投注卡槽
     * "input": 101,//投注数量
     * "output": 1515,//产出数量
     * "is_hit": 0
     * {
     * "round_id": 20210811174440,
     * "slot": 2,
     * "input": 100,
     * "output": 1000,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174440,
     * "slot": 3,
     * "input": 400,
     * "output": 4000,
     * "is_hit": 1
     * },
     * {
     * "round_id": 20210811174440,
     * "slot": 4,
     * "input": 500,
     * "output": 3500,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174440,
     * "slot": 5,
     * "input": 400,
     * "output": 1600,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174440,
     * "slot": 6,
     * "input": 100,
     * "output": 400,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174440,
     * "slot": 7,
     * "input": 100,
     * "output": 700,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174440,
     * "slot": 8,
     * "input": 100,
     * "output": 700,
     * "is_hit": 0
     * }
     * ]
     * },
     * {
     * "id": 20210811174520,
     * "hit_slot": 1,
     * "created_at": "2021-08-11 17:45:20.094325",
     * "bet": [
     * {
     * "round_id": 20210811174520,
     * "slot": 1,
     * "input": 101,
     * "output": 1515,
     * "is_hit": 1
     * },
     * {
     * "round_id": 20210811174520,
     * "slot": 2,
     * "input": 101,
     * "output": 1010,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174520,
     * "slot": 3,
     * "input": 101,
     * "output": 1010,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174520,
     * "slot": 4,
     * "input": 101,
     * "output": 707,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174520,
     * "slot": 5,
     * "input": 101,
     * "output": 404,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174520,
     * "slot": 6,
     * "input": 101,
     * "output": 404,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174520,
     * "slot": 7,
     * "input": 101,
     * "output": 707,
     * "is_hit": 0
     * },
     * {
     * "round_id": 20210811174520,
     * "slot": 8,
     * "input": 101,
     * "output": 707,
     * "is_hit": 0
     * }
     * ]
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    //单个用户游戏纪录查询 多行
    public function userGamelogList(Request $request)
    {

        $data = $request->only(['page', "page_size", 'user_id', 'nickname', 'start_time', 'end_time']);

        $va = app('validator')->make($data, [
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1',
            'user_id' => 'integer|min:1',
            'nickname' => 'string|max:32',
            'start_time' => 'integer|min:1',
            'end_time' => 'integer|min:1'
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 10;

        if (isset($data['user_id'])) {
            $whereUser[] = ['id', '=', $data['user_id']];

        }
        if (isset($data['nickname'])) {
            $whereUser[] = ['nickname', '=', $data['nickname']];

        }
        if (empty($whereUser)) {
            throw  new BasicException(10001, '用户id与用户昵称必须写一个');
        }


        if (isset($data['start_time'])) {
            $where[] = ['created_at', '>', date('Y-m-d H:i:s', $data['start_time'])];
        }

        if (isset($data['end_time'])) {
            $where[] = ['created_at', '<', date('Y-m-d H:i:s', $data['end_time'])];
        }

        $userInfo = app('model_game_user')
            ->where($whereUser)
            ->first();

        if (empty($userInfo)) {
            throw  new BasicException(10001, '没有用户信息');
        }

        if (isset($where)) {
            $list = app('model_game_round')
                ->where($where)
                ->with(['bet' => function ($query) use ($userInfo) {
                    $query->select(['round_id', 'slot', 'input', 'output', 'is_hit']);
                }])
                ->whereHas('bet', function ($query) use ($userInfo) {
                    $query->where('user_id', $userInfo->id)->orderBy('id', 'desc');
                })
                ->paginate($data['page_size'], ['id', 'hit_slot', 'created_at'], '', $data['page'])
                ->toArray();
        } else {
            $list = app('model_game_round')
                ->with(['bet' => function ($query) use ($userInfo) {
                    $query->select(['round_id', 'slot', 'input', 'output', 'is_hit']);
                }])
                ->whereHas('bet', function ($query) use ($userInfo) {
                    $query->where('user_id', $userInfo->id)->orderBy('id', 'desc');
                })
                ->paginate($data['page_size'], ['id', 'hit_slot', 'created_at'], '', $data['page'])
                ->toArray();
        }

        $result = [
            'total' => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page' => $list['last_page'] ?? 1,
            'userInfo' => [
                'id' => $userInfo->id,
                'nickname' => $userInfo->nickname
            ],
            'list' => $list['data']

        ];
        return Response::sendData($result);

    }

    //合成纪录

    /**
     * @api {get} /guessing/user/prolog 合成纪录
     * @apiVersion 0.1.0
     * @apiName 合成纪录
     * @apiGroup 霍克城堡 竞猜
     * @apiParam {Int}                     page  （选填）
     * @apiParam {Int}                     page_size  （选填）
     * @apiParam {Int}                     user_id  （选填）
     * @apiParam {String}                  nickname 用户昵称（选填）
     * @apiParam {Int}                     start_time 开始时间 （选填）
     * @apiParam {Int}                     end_time 结束时间 （选填）
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "total": 11,
     * "current_page": 1,
     * "last_page": 6,
     * "list": [
     * {
     * "id": 1,
     * "user_id": 547900,
     * "product_id": 1,//绑定产品ID
     * "sku_id": 1,

     * "name": "萤火之森",//商品名 当type==gift为商品名 type==balance时显示为蓝钻
     * "price": 1,//单价 物品价值
     * "count": 1,//数量    消耗=单价*数量

     * "is_send": 1,
     * "created_at": "2021-07-30 14:09:46.790728",//合成时间
     * "updated_at": "2021-07-30 14:09:46.879271",
     * "user": {
     * "id": 547900,
     * "nickname": "提莫队长呢"
     * }
     * },
     * {
     * "id": 2,
     * "user_id": 547900,
     * "product_id": 1,
     * "sku_id": 1,
     * "name": "萤火之森",
     * "price": 1,
     * "count": 1,
     * "is_send": 1,
     * "created_at": "2021-07-30 14:10:17.743422",
     * "updated_at": "2021-07-30 14:10:17.799573",
     * "user": {
     * "id": 547900,
     * "nickname": "提莫队长呢"
     * }
     * }
     * ]
     * }
     * }
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function orderList(Request $request)
    {
        $data = $request->only(['page', 'page_size', 'user_id', 'nickname', 'start_time', 'end_time']);
        $va = app('validator')->make($data, [
            'page' => 'integer|min:1',
            'page_size' => 'integer|min:1',
            'user_id' => 'integer|min:1',
            'nickname' => 'string|min:1',
            'start_time' => 'integer|min:1',
            'end_time' => 'integer|min:1'
        ]);
        if ($va->fails()) {
            throw  new BasicException(10001, $va->errors()->first());
        }
        $data['page'] = $data['page'] ?? 1;
        $data['page_size'] = $data['page_size'] ?? 10;
        $data['nickname'] = $data['nickname'] ?? '';

        if (isset($data['user_id'])) {
            $where[] = ['user_id', '=', $data['user_id']];
        }


        $whereWith[] = ['nickname', 'like', '%' . $data['nickname'] . '%'];

        if (isset($data['start_time'])) {
            $where[] = ['created_at', '>', date('Y-m-d H:i:s', $data['start_time'])];
        }
        if (isset($data['end_time'])) {
            $where[] = ['created_at', '<', date('Y-m-d H:i:s', $data['end_time'])];
        }

        if (!empty($data['user_id'])) {
            $where[] = ['user_id', '=', $data['user_id']];
        }
        if (isset($where)) {

            $list = app('model_game_order')
                ->whereHas('user', function ($query) use ($whereWith) {
                    $query->where($whereWith);
                })
                ->with(['user' => function ($query) {
                    $query->select(['id', 'nickname']);
                }])
                ->where($where)
                ->orderBy('id', 'desc')
                ->paginate($data['page_size'], ['*'], '', $data['page'])
                ->toArray();
        } else {

            $list = app('model_game_order')
                ->whereHas('user', function ($query) use ($whereWith) {
                    $query->where($whereWith);
                })
                ->with(['user' => function ($query) {
                    $query->select(['id', 'nickname']);
                }])
                ->orderBy('id', 'desc')
                ->paginate($data['page_size'], ['*'], '', $data['page'])
                ->toArray();
        }


        $result = [
            'total' => $list['total'] ?? 0,
            'current_page' => $list['current_page'] ?? 1,
            'last_page' => $list['last_page'] ?? 1,
            'list' => $list['data']
        ];
        return Response::sendData($result);
    }






    //

    /**
     * @api {get} /guessing/user/bet 最新一轮每个槽位投注情况
     * @apiVersion 0.1.0
     * @apiName 最新一轮每个槽位投注情况
     * @apiGroup 霍克城堡 竞猜
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": [
     * {
     * "sum(input)": "10",
     * "slot": 1 //slot 必定是1-8
     * },
     * {
     * "sum(input)": "10",
     * "slot": 2
     * },
     * {
     * "sum(input)": "10",
     * "slot": 3
     * },
     * {
     * "sum(input)": "10",
     * "slot": 4
     * },
     * {
     * "sum(input)": "10",
     * "slot": 5
     * },
     * {
     * "sum(input)": "10",
     * "slot": 6
     * },
     * {
     * "sum(input)": "10",
     * "slot": 7
     * },
     * {
     * "sum(input)": "100",//下注数量
     * "slot": 8//投注槽位
     * }
     * ]
     * }
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function statisticBet(Request $request)
    {
        $maxRound = app('model_game_bet')->max('round_id');
        $statisticBet = app('model_game_bet')->selectRaw('sum(input),slot')->where('round_id', $maxRound)->orderBy('slot')->groupBy('slot')->get()->toArray();
        $isHaveEight = array_column($statisticBet, 'slot');

        foreach ([1, 2, 3, 4, 5, 6, 7, 8] as $v) {
            if (!in_array($v, $isHaveEight)) {
                array_push($statisticBet, ['sum(input)' => 0, 'slot' => $v]);
            }
        }
        foreach ($statisticBet as $val) {
            $key_arrays[] = $val['slot'];
        }
        array_multisort($key_arrays, SORT_ASC, SORT_NUMERIC, $statisticBet);
        return Response::sendData($statisticBet);
    }

}


